<?php

// phpMyRealty 3
//
// File Name: viewlisting.php
// File Location : ./
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');

include ( './config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// View Listing SECTION

// Check the id variable
if (isset($_GET['id']) && eregi('^[0-9]+$', $_GET['id'])) {

	// Title/descr language to use (if available)
	$title = str_replace( 'name', 'title', $language_in );
	$description = str_replace( 'name', 'description', $language_in );

	$sql = 'SELECT ' . $title . ', ' . $description . ', mls, type, type2, zip, address1, address2, title, description FROM ' . PROPERTIES_TABLE  . ' WHERE approved = 1 AND id = "' . safehtml($_GET['id']) . '" LIMIT 1';
	$r_title = $db->query ( $sql );
	$f_title = $db->fetcharray ( $r_title );

	if ($db->numrows($r_title) == 0)
		die ('Listing does not exist');

	// Add the listing into the 'Recently Visited' list
	visitedListingsAdd($_GET['id']);

}

// Default
if ($f_title[0] == '')
	$f_title[0] = $f_title['title'];

if ($f_title[1] == '')
	$f_title[1] = $f_title['description'];

// Title tag content
$title = $conf['website_name_short'] . ' - ' . $f_title[0];

$initAjax = TRUE;

include ( PATH . '/includes/ajaxFavorites.php');

$initiate_maps = 'ON';

$meta_title = trim(removehtml(unsafehtml_xml($f_title[0])));
$meta_description = removehtml(unsafehtml_xml($f_title[1]));
$meta_description = trim(substr($meta_description, 0, 160));
$meta_keywords = trim(removehtml(unsafehtml_xml($f_title[0]) . ', ' . getnamebyid(TYPES2_TABLE, $f_title['type2']) . ', ' . getnamebyid(TYPES_TABLE, $f_title['type']) . ', ' . $f_title['zip'] . ', ' . $f_title['mls']));

// Template header
include ( PATH . '/templates/' . $cookie_template . '/header.php' );

// Check the id variable
if (isset($_GET['id']) && eregi('^[0-9]+$', $_GET['id']))

 {

  // Navigation
  echo table_header ( $lang['Navigation'] );
  // Home link
  echo '- <a href="' . URL . '/">' . $lang['Menu_Home'] . '</a><br />';

  $usersearch = $session->fetch('usersearchvariables');
  $listingsearch = $session->fetch('listingsearchvariables');
  // Show user search link (using cached results)
  if (!empty($usersearch))
   echo '- <a href="' . URL . '/usersearch.php?' . $session->fetch('usersearchvariables') . '">' . $lang['Search_Back_User'] . '</a><br />';
  // Show listings search link (using cached results)
  if (!empty($listingsearch))
   echo '- <a href="' . URL . '/search.php?' . $session->fetch('listingsearchvariables') . '">' . $lang['Search_Back_Listing'] . '</a><br />';

  echo table_footer ();

  //

  // Update HITS counter


  $sql = 'SELECT id FROM ' . PROPERTIES_TABLE  . ' WHERE approved = 1 AND id = "' . safehtml($_GET['id']) . '" LIMIT 1';
  $r_if_exist_test = $db->query ( $sql ) or die (mysql_error());

 // Check if the listing exists, if not, show nothing.
 if ($db->numrows($r_if_exist_test) > 0)
  {

  $sql = 'UPDATE ' . PROPERTIES_TABLE  . ' SET hits = hits+1 WHERE approved = 1 AND id = "' . safehtml($_GET['id']) . '" LIMIT 1';

  if ( $session->fetch('listing_counter_id') != $_GET['id']
  || (time() - $session->fetch('listing_counter_time')) > 60*60*24 )
   {
    $db->query ( $sql ) or error ('Critical Error' , mysql_error());
   }
  // Cache the last listing id not to allow this user
  // to be counted next time he visit this listing
  // This variable stores id and time to allow the counter
  // be updated in 24 hours even if this user did not visit
  // any other listing to empty the cached data
  $session->set('listing_counter_id', intval($_GET['id']));
  $session->set('listing_counter_time', time());

  //

  // Fetch the package data for this user (agent)

  $sql = 'SELECT * FROM ' . PROPERTIES_TABLE  . ' WHERE approved = 1 AND id = ' . intval($_GET['id']) . ' LIMIT 1';
  $r_listing = $db->query ( $sql );
  $f_listing = $db->fetcharray ( $r_listing );

  $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = ' . $f_listing['userid'] . ' LIMIT 1';
  $r_user = $db->query ( $sql );
  $f_user = $db->fetcharray ( $r_user );

  if ($f_user['package'] != '0' && $f_user['package'] != '')
   {

    $sql = 'SELECT * FROM ' . PACKAGES_AGENT_TABLE  . ' WHERE id = ' . $f_user['package'] . ' LIMIT 1';
    $r_package = $db->query ( $sql );
    $f_package = $db->fetcharray ( $r_package );

   }

  else

   {

    $f_package['listings'] = $conf['free_listings'];
    $f_package['gallery'] = $conf['free_gallery'];
    $f_package['mainimage'] = $conf['free_mainimage'];
    $f_package['photo'] = $conf['free_photo'];
    $f_package['phone'] = $conf['free_phone'];
    $f_package['address'] = $conf['free_address'];

   }

  // End of packages
  $title = str_replace( 'name', 'title', $language_in );
  $description = str_replace( 'name', 'description', $language_in );

  $sql = 'SELECT ' . $title . ', ' . $description . ', ' . PROPERTIES_TABLE . '.* FROM ' . PROPERTIES_TABLE  . ' WHERE approved = 1 AND id = "' . safehtml($_GET['id']) . '" LIMIT 1';
  $r = $db->query ( $sql ) or error ('Critical Error' , mysql_error());

  echo '
   <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';

  $f = $db->fetcharray( $r );

	// Default
    if (trim($f[0]) != '')
        $f['title'] = trim($f[0]);

    if (trim($f[1]) != '')
        $f['description'] = trim($f[1]);

  // Starting a new template
  $template = new Template;

  $tpl = implode ('', file( PATH . '/templates/' . $cookie_template . '/tpl/property_detailed.tpl' ));

  // Load listing short search results template
  $template->load ( $tpl );

  // Make all values in the array 'n/a' if empty
  $f = array_map ( 'if_empty', $f);

  // Replace the template variables
  $template->set ( 'print', '<a href="' . URL . '/print.php?id=' . $f['id'] . '" target="_blank"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/print.png" border="0" alt=""><br />' . $lang['Listing_Print'] . '</a>' );

  if ($f_package['mainimage'] == 'ON')
   $template->set ( 'image', show_gallery_image ('images', $f['id']) );
  else
   $template->set ( 'image', '' );

	function my_rowcode($thekey, $thevalue) {
		if (!$thevalue OR strtolower($thevalue) == 'none') return '';
		return '
          <tr>
            <td><span class="nameDetailed">{@'.$thekey.'}:</font></td>
            <td><span class="valueDetailed">'.$thevalue.'</span></td>
          </tr>
		';
	}

    $f['status'] = my_rowcode('status', getnamebyid ( STATUS_TABLE, $f['status'] ));
    if (strcasecmp($conf['show_mls'], 'OFF')) {
	    $f['mls'] = my_rowcode('mls', $f['mls']);
    } else {
        $f['mls'] = '';
    }
	$f['type'] = my_rowcode('type',getnamebyid ( TYPES_TABLE, $f['type'] ));
	$f['type2'] = my_rowcode('type2', getnamebyid (TYPES2_TABLE, $f['type2']));

	$f['style'] = my_rowcode('style',getnamebyid ( STYLES_TABLE, $f['style'] ));
	$f['size'] = my_rowcode('lot_size',$f['size']);
	$f['dimensions'] = my_rowcode('dimensions',$f['dimensions']);

	$f['half_bathrooms'] = my_rowcode('half_bathrooms', $f['half_bathrooms'] );
	$template->set ('my_price', my_rowcode('price', $conf['currency'].' '.number_format($f['price']) ));

	$f['directions'] = my_rowcode('directions', $f['directions'] );
	$f['year_built'] = my_rowcode('year_built', $f['year_built'] );
	$f['buildings'] = my_rowcode('buildings', show_multiple ( BUILDINGS_TABLE, $f['buildings'] ) );
	$f['appliances'] = my_rowcode('appliances', show_multiple ( APPLIANCES_TABLE, $f['appliances'] ) );
	$f['features'] = my_rowcode('features', show_multiple ( FEATURES_TABLE, $f['features'] ) );
	$f['garage'] = my_rowcode('garage', getnamebyid ( GARAGE_TABLE, $f['garage'] ) );
	$f['basement'] = my_rowcode('basement', getnamebyid ( BASEMENT_TABLE, $f['basement'] ) );
	$template->set ( 'date_added2', my_rowcode('date_added', printdate($f['date_added']) ));
	$template->set ( 'date_updated2', my_rowcode('date_updated', printdate($f['date_updated']) ));
	$template->set ( 'date_upgraded2', my_rowcode('date_upgraded', printdate($f['date_upgraded']) ));
	
	// Custom fields
	
	// Check if custom field is input, if it is, it will have {INPUT}{value} in the database, otherwise, it will have a primary key reference
	$custom_fields = array(
						'custom1' => $f['custom1'],
						'custom2' => $f['custom2'],
						'custom3' => $f['custom3'],
						'custom4' => $f['custom4'],
						'custom5' => $f['custom5'],
						'custom6' => $f['custom6'],
						'custom7' => $f['custom7'],
						'custom8' => $f['custom8'],
						'custom9' => $f['custom9'],
						'custom10' => $f['custom10'],
	);
	foreach ( $custom_fields AS $key => $value )
	{
		if ( strpos( $value, '{INPUT}' ) !== false )
		{
			// Input box
			$f[$key] = my_rowcode( $key, str_replace( '{INPUT}', '', $value ) );
		}
		else
		{
			// Select box
			$f[$key] = my_rowcode( $key, show_custom_value ( $db, $f[$key],  VALUES_TABLE ) );
		}
	}

	$template->set ( 'custom1', $f['custom1'] );
	$template->set ( 'custom2', $f['custom2'] );
	$template->set ( 'custom3', $f['custom3'] );
	$template->set ( 'custom4', $f['custom4'] );
	$template->set ( 'custom5', $f['custom5'] );
	$template->set ( 'custom6', $f['custom6'] );
	$template->set ( 'custom7', $f['custom7'] );
	$template->set ( 'custom8', $f['custom8'] );
	$template->set ( 'custom9', $f['custom9'] );
	$template->set ( 'custom10', $f['custom10'] );

    $template->set ( 'status', $f['status'] );
	$template->set ( 'mls', $f['mls'] );
	$template->set ( 'title', $f['title'] );
	$template->set ( 'type', $f['type'] );
	$template->set ( 'type2', $f['type2'] );
	$template->set ( 'style', $f['style'] );
	$template->set ( 'description', unsafehtml($f['description']) );
	$template->set ( 'lot_size', $f['size'] );
	$template->set ( 'dimensions', $f['dimensions'] );

  $my_images = URL . '/templates/' . $cookie_template . '/images';
  $my_bedbathcar = '';

  if ($f['bedrooms'] < 1) {
	$template->set ( 'bedrooms', '' );
	$template->set ( 'bedrooms2','' );
  } else {
	$template->set ( 'bedrooms2', my_rowcode('bedrooms', $f['bedrooms']) );
	$template->set ( 'bedrooms', $f['bedrooms'] );
	$my_bedbathcar .= '
	     <tr>
	       <td align="center"><img src="'.$my_images.'/bed.gif" alt="" /> '.$f['bedrooms'].'</td>
	     </tr>
	';
  }

  if ($f['bathrooms'] < 1) {
	$template->set ( 'bathrooms', '' );
	$template->set ( 'bathrooms2','' );
  } else {
	$template->set ( 'bathrooms2', my_rowcode('bathrooms', $f['bathrooms']) );
	$template->set ( 'bathrooms', $f['bathrooms'] );
	$my_bedbathcar .= '
	     <tr>
	       <td align="center"><img src="'.$my_images.'/bath.gif" alt="" /> '.$f['bathrooms'].'</td>
	     </tr>
	';
  }

  if ($f['garage_cars'] < 1) {
	$template->set ( 'garage_cars', '' );
	$template->set ( 'garage_cars2','' );
  } else {
	$template->set ( 'garage_cars2', my_rowcode('garage_cars', $f['garage_cars']) );
	$template->set ( 'garage_cars', $f['garage_cars'] );
	$my_bedbathcar .= '
	     <tr>
	       <td align="center"><img src="'.$my_images.'/car.gif" alt="" /> '.$f['garage_cars'].'</td>
	     </tr>
	';
  }

  if ($my_bedbathcar) {
	  $my_bedbathcar = '
	   <td valign="top" align="center">
	    <table width="100%" border="0" cellspacing="0" cellpadding="10">
			'.$my_bedbathcar.'
	    </table>
	   </td>
	';
  }
  $template->set ( 'my_bedbathcar', $my_bedbathcar );

  $template->set ( 'half_bathrooms', $f['half_bathrooms'] );

  $cat = explode ("#", $f['location2']);
  $r11 = $db->query('SELECT category FROM ' . LOCATION1_TABLE . ' WHERE selector = "' . $cat[0] . '"');
  $f11 = $db->fetcharray($r11);
  $template->set ( 'location1', $f11['category'] );

  $r22 = $db->query('SELECT subcategory FROM ' . LOCATION2_TABLE . ' WHERE catsubsel = "' . $cat[1] . '"');
  $f22 = $db->fetcharray($r22);
  $template->set ( 'location2', $f22['subcategory'] );

  $r33 = $db->query('SELECT subsubcategory FROM ' . LOCATION3_TABLE . ' WHERE catsubsubsel = "' . $cat[2] . '"');
  $f33 = $db->fetcharray($r33);
  $template->set ( 'location3', $f33['subsubcategory'] );


  $f['location'] = my_rowcode('location', $f['address1'].' '.$f['address2'].' '.$f33['subsubcategory'].' '.$f22['subcategory'].' '.$f['zip'].' '.$f11['category']);
  $template->set ( 'location', $f['location']);




  // Do not show address if it is not allowed in the listing
  if ($f['display_address'] == 'YES' &&  $f_package['address'] == 'ON')
   {
    $template->set ( 'address1', $f['address1'] );
    $template->set ( 'address2', $f['address2'] . '<br />' );
    $template->set ( 'zip', $f['zip'] );
   }
  elseif ($f['display_address'] != 'YES' || $f_package['address'] != 'ON')
   {
    $template->set ( 'address1', ' ' );
    $template->set ( 'address2', ' ' );
    $template->set ( 'zip', ' ' );
   }

  $template->set ( 'price', pmr_number_format($f['price']) );
  $template->set ( 'currency', $conf['currency'] );

  $template->set ( 'directions', unsafehtml( $f['directions'] ) );

//  unset($directions);

  // DIRECTIONS : END

  // Mail to a friend
  if ($conf['rewrite'] == 'ON')
   $template->set ( 'friend', '<a href="' . URL . '/Friend/' . $f['id'] . '.html"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/friend.png" border="0" alt=""><br />' . $lang['Mail_Friend'] . '</a>' );
  else
   $template->set ( 'friend', '<a href="' . URL . '/friend.php?id=' . $f['id'] . '"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/friend.png" border="0" alt=""><br />' . $lang['Mail_Friend'] . '</a>' );

  $template->set ( 'year_built', $f['year_built'] );
  $template->set ( 'buildings', $f['buildings'] );
  $template->set ( 'appliances', $f['appliances'] );
  $template->set ( 'features', $f['features'] );
  $template->set ( 'garage', $f['garage'] );
  $template->set ( 'basement', $f['basement'] );
  $template->set ( 'date_added', printdate($f['date_added']) );
  $template->set ( 'date_updated', printdate($f['date_updated']) );
  $template->set ( 'date_upgraded', printdate($f['date_upgraded']) );
  $template->set ( 'ip_added', $f['ip_added'] );
  $template->set ( 'ip_updated', $f['ip_updated'] );
  $template->set ( 'ip_upgraded', $f['ip_upgraded'] );
  $template->set ( 'hits', $f['hits'] );

 if (!isset($slideshow) || $slideshow == '' || $slideshow == '1') {

  $sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = "' . $f['id'] . '" ORDER BY id';
  $r_gallery = $db->query( $sql ) or error ('Critical Error', mysql_error ());

  if (file_exists( PATH . '/images/' . $f['id'] . '.jpg') || $db->numrows($r_gallery) > 0 ) {

   $gallery_in = '

   <script language="javascript" type="text/javascript" src="' . URL . '/includes/js/swfobject.js" ></script>

   <!-- Div that contains gallery. -->
   <div id="gallery">
   <h1>No flash player!</h1>
   <p>It looks like you don\'t have flash player installed. <a href="http://www.macromedia.com/go/getflashplayer" >Click here</a> to go to Macromedia download page.</p>
   </div>

   <!-- Script that embeds gallery. -->
   <script language="javascript" type="text/javascript">
   var so = new SWFObject("' . URL . '/includes/flash/flashgallery.swf", "gallery", "500", "400", "8");
   so.addParam("quality", "high");
   so.addParam("allowFullScreen", "true");
   so.addVariable("color_path","' . URL . '/includes/flash/default.xml");
   so.addVariable("script_path","' . URL . '/flashgallery.php?id=' . $f['id'] . '&random=' . rand(0,999999). '");
   so.write("gallery");
   </script>
   ';

   $template->set ( 'slideshow' , $gallery_in);

  }

  else

   $template->set ( 'slideshow' , '');





 }
 elseif (isset($slideshow) && $slideshow == '2')
 {

  $sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = "' . $f['id'] . '" ORDER BY id';
  $r_gallery = $db->query( $sql ) or error ('Critical Error', mysql_error ());

  if (file_exists( PATH . '/images/' . $f['id'] . '.jpg') || $db->numrows($r_gallery) > 0 ) {

  $gallery_in = '
  <script src="' . URL . '/includes/dhonishow/jquery.js" type="text/javascript" charset="utf-8"></script>
  <script src="' . URL . '/includes/dhonishow/dhonishow.js" type="text/javascript" charset="utf-8"></script>
  ';

  $gallery_in .= '
  <div class="dhonishow"> ';

  if (file_exists( PATH . '/images/' . $f['id'] . '.jpg'))
   $gallery_in .= '<img src="' . URL . '/images/' . $f['id'] . '.jpg" alt="Main Image"/>' . "\n";

  $sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = "' . $f['id'] . '" ORDER BY id';
  $r_gallery = $db->query( $sql ) or error ('Critical Error', mysql_error ());

  if ($db->numrows($r_gallery) > 0) {
   while ($f_gallery = $db->fetcharray($r_gallery)) {
    $gallery_in .= '<img src="' . URL . '/gallery/' . $f_gallery['id'] . '.jpg" alt="' . $f_gallery['title']. '" />' . "\n";
   }
  }

  $gallery_in .= '
  </div> ';

  $template->set ( 'slideshow' , $gallery_in);

  }

  else

   $template->set ( 'slideshow' , '');

 }
 else
  $template->set ( 'slideshow' , '');

  // View realtor name
  $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE approved = 1 AND id = ' . $f['userid'] . ' LIMIT 1';
  $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
  $f_user = $db->fetcharray ($r_user);

  if ($conf['rewrite'] == 'ON')
   $template->set ( 'view_realtor', '<a href="' . URL . '/Realtor/' . $f['userid'] . '.html">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>'  );
  else
   $template->set ( 'view_realtor', '<a href="' . URL . '/viewuser.php?id=' . $f['userid'] . '">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>');

  $template->set ( 'favorites_image', '<img src="' . URL . '/templates/' . $cookie_template . '/images/icons/add-favorite.png" border="0" alt="">');

  if (favoriteListingsCheck($f['id'])) {
   $template->set ( 'favorites', '<div id="favorites-' . $f['id'] . '" name="favorites-' . $f['id'] . '" style="display: inline"><span style="cursor: pointer; display: block;" class="favorites" onclick="javascript:xajax_favorites_remove(\'' . $f['id'] . '\');">' . $lang['Favorites_Remove'] . '</span></div>');
  } else {
   $template->set ( 'favorites', '<div id="favorites-' . $f['id'] . '" name="favorites-' . $f['id'] . '" style="display: inline"><span style="cursor: pointer; display: block;" class="favorites" onclick="javascript:xajax_favorites(\'' . $f['id'] . '\');">' . $lang['Favorites_Add'] . '</span></div>');
  }

  // Relator Details

  $template->set ( 'realtor_first_name', $f_user['first_name'] );
  $template->set ( 'realtor_last_name', $f_user['last_name'] );
  $template->set ( 'realtor_company_name', $f_user['company_name'] );

  if ($f_package['phone'] == 'ON')
   {
    $template->set ( 'realtor_phone', $f_user['phone'] );
    $template->set ( 'realtor_fax', $f_user['fax'] );
    $template->set ( 'realtor_mobile', $f_user['mobile'] );
   }
  else
   {
    $template->set ( 'realtor_phone', '' );
    $template->set ( 'realtor_fax', '' );
    $template->set ( 'realtor_mobile', '' );
   }

  $template->set ( 'realtor_mail', validateemail ( $f['userid'], $f_user['email'], $f['id'] ) . '<img src="' . URL . '/templates/' . $cookie_template . '/images/icons/email.png" border="0" alt=""><br />' . $lang['Realtor_Send_Message'] . '</a>' );

	// Test for video file
	if (file_exists(PATH . '/video/' . $f['id'] . '.flv'))
	{

		$template->set ( 'video2' , '<p align="center">
		<!-- start of flv player -->
		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8" width="450" height="367" id="theMediaPlayer">
		<param name=movie value="' . URL . '/includes/flash/flvplayer.swf">
		<param name=quality value="high">
		<param name=bgcolor value="#FFFFFF">
		<param name=allowFullScreen value="false">
		<param name=swLiveConnect value="true">
		<param name=allowScriptAccess value="sameDomain">
		<param name="FlashVars" value="file=' . URL . '/video/' . $f['id'] . '.flv&width=450&height=367&displaywidth=450&displayheight=347&overstretch=true&autostart=false&showfsbutton=false&logo=&link=&linktarget=_blank&backcolor=0xFFFFFF">
		<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="450" height="367" bgcolor="#FFFFFF" name="theMediaPlayer" src="' . URL . '/includes/flash/flvplayer.swf" flashvars="file=' . URL . '/video/' . $f['id'] . '.flv&width=450&height=367&displaywidth=450&displayheight=347&overstretch=true&autostart=false&showfsbutton=false&logo=&link=&linktarget=_blank&backcolor=0xFFFFFF">
		</embed>
		</object>
		<!-- end of flv player -->
		</p>
		<center><a href="javascript:void(0);" onClick="hidediv(\'show_video\');">Hide Video</a></center>');

		$video2 = true;

	}
	else
	{
		$template->set ( 'video2' , '');
		$video2 = false;

	}

	// Test for video link
	if ($f['video'] == '')
		$video = false;
	else
		$video = true;

	if ($video == false && $video2 == false)
	{
		// Deactivate the link
		$template->set ( 'video', '<a href="javascript:void(0);"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/video.png" border="0" alt=""><br />' . $lang['Video_Tour'] . '</a>');
	}
	elseif ($video2 == true)
	{
		$template->set ( 'video', '<a href="javascript:void(0);" onClick="showdiv(\'show_video\');"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/video.png" border="0" alt=""><br />' . $lang['Video_Tour'] . '</a>');
	}
	elseif ($video == true)
	{
		$template->set ( 'video', '<a href="' . $f['video'] . '" target="_blank"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/video.png" border="0" alt=""><br />' . $lang['Video_Tour'] . '</a>');
	}

  $template->set ( 'pdf', '<a href="' . URL . '/pdf.php?id=' . $f['id'] . '" target="_blank"><img src="' . URL . '/templates/' . $cookie_template . '/images/icons/pdf.gif" width="32" height="32" border="0" alt=""><br />PDF</a>' );

  $template->set ( 'new', newitem ( PROPERTIES_TABLE, $f['id'], $conf['new_days']) );
  $template->set ( 'updated', updateditem ( PROPERTIES_TABLE, $f['id'], $conf['updated_days']) );
  $template->set ( 'featured', featureditem ( $f['featured'] ) );

	// If show calendar
	if ($conf['show_calendar'] == 'ON')
	{
		$template->set ( 'show_calendar', '<p><a href="#" rel="tab4"><span class="tab_title">{@calendar}</span></a></p>' );
	}
		else
	{
		$template->set ( 'show_calendar', '' );
	}

  $calendar_tpl = '

<br />
<div id="calendar-container">
 <script type="text/javascript">
  var selectedDate = new Array("' . implode('", "', explode(',', $f['calendar'])) . '", "01/01/2099", "01/02/2099");

  function dateSelected(year, month, day) {
    var datein = selectedDate;

    month = month+1; if (month < 10) month = "0"+month;

	day = day+1; if (day < 10) day = "0" + day;

    for (var i = 0; i < datein.length; i++) {
     if (datein[i] == month + "/" + day + "/" + year) {
      return true;
     }
    }
  return false;
  };

  Calendar.setup(
    {
      flat         : "calendar-container", // ID of the parent element
      dateStatusFunc : function(date, y, m, d) {
                         if (dateSelected(y, m, d)) return "special";
                         else return true;
                       }
    }
  );
</script>
</div>

  ';

  $template->set ( '@calendar', $lang['Availability_Calendar'] );
  $template->set ( 'calendar', $calendar_tpl );

  // Defaults for their account type
  $paid_account = false;
  $account = false;
  $agent_details = '';

  	// If they have an account
  	if (auth_check($session->fetch('login'), $session->fetch('password')))
  	{
		  // Fetching the user ID from the user's table
		  $sql = 'SELECT approved, id, package FROM ' . USERS_TABLE . ' WHERE login = "' . $session->fetch('login') . '" LIMIT 1';
		  $r_agent = $db->query( $sql );
		  $f_agent = $db->fetcharray( $r_agent );

		  $account = true;

		  if ($f_agent['package'] > 0)
		  	$paid_account = true;
		  else
		  	$paid_account = false;
  	}
  	else
  	{
  		$paid_account = false;
  		$account = false;
  	}

	// Agent details (whether this displays is configurable via admin panel > configuration settings)

	// If anyone can view agent details or registered only but they are logged in or paid only but they are paid
	if ($conf['contact_agents'] == '1' || $paid_account == true || ($conf['contact_agents'] == '2' && $account == true))
	{

		if ($conf['rewrite'] == 'ON')
			$view_realtor = '<a href="' . URL . '/Realtor/' . $f['userid'] . '.html">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>';
		else
			$view_realtor = '<a href="' . URL . '/viewuser.php?id=' . $f['userid'] . '">' . $f_user['first_name'] . ' ' . $f_user['last_name'] . '</a>';

		$template->set ( 'realtor_website', validatewebsite ( $f['userid'], $f_user['website'] ) . '<img src="' . URL . '/templates/' . $cookie_template . '/images/icons/www.png" border="0" alt=""><br />' . $lang['Realtor_Visit_Website'] . '</a>');

		$agent_details .= '
		<tr>
			<th width="30%"><span class="nameDetailed">' . $lang['View_Realtor'] . ':</span></th>
			<td width="70%"><span class="valueDetailed">' . $view_realtor . '</span></td>
		</tr>
		<tr>
			<th><span class="nameDetailed">' . $lang['Realtor_Company_Name'] . ':</span></th>
			<td><span class="valueDetailed">' . $f_user['company_name'] . '</span></td>
		</tr>
		';

		if ($f_package['phone'] == 'ON')
		{
			$agent_details .= '
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Phone'] . ':</span></th>
				<td><span class="valueDetailed">' . $f_user['phone'] . '</span></td>
			</tr>
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Fax'] . ':</span></th>
				<td><span class="valueDetailed">' . $f_user['fax'] . '</span></td>
			</tr>
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Mobile'] . ':</span></th>
				<td><span class="valueDetailed">' . $f_user['mobile'] . '</span></td>
			</tr>
			';
		}
		else
		{
			$agent_details .= '
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Phone'] . ':</span></th>
				<td><span class="valueDetailed"></span></td>
			</tr>
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Fax'] . ':</span></th>
				<td><span class="valueDetailed"></span></td>
			</tr>
			<tr>
				<th><span class="nameDetailed">' . $lang['Realtor_Mobile'] . ':</span></th>
				<td><span class="valueDetailed"></span></td>
			</tr>
			';
		}
	}
	// Account only, but they don't have an account
	elseif ($conf['contact_agents'] == '2' && $account == false)
	{
		$agent_details .= $lang['Agent_Details_Account_Only'];

		$template->set ( 'realtor_website', '' . '<img src="' . URL . '/templates/' . $cookie_template . '/images/icons/www.png" border="0" alt=""><br />' . $lang['Realtor_Visit_Website'] . '</a>');
	}
	// Paid account only, but they don't have a paid account
	elseif ($conf['contact_agents'] == '3' && $paid_account == false)
	{
		$agent_details .= $lang['Agent_Details_Pay_Only'];

		$template->set ( 'realtor_website', '' . '<img src="' . URL . '/templates/' . $cookie_template . '/images/icons/www.png" border="0" alt=""><br />' . $lang['Realtor_Visit_Website'] . '</a>');
	}

	$template->set ( 'agent_details', $agent_details );

  // Names of the variables

  $template->set ( '@status', $lang['Listing_Status'] );
  $template->set ( '@mls', $lang['Listing_MLS'] );
  $template->set ( '@title', $lang['Listing_Title'] );
  $template->set ( '@type', $lang['Listing_Property_Type'] );
  $template->set ( '@type2', $lang['Module_Listing_Type'] );
  $template->set ( '@style', $lang['Listing_Style'] );
  $template->set ( '@description', $lang['Listing_Description'] );
  $template->set ( '@lot_size', $lang['Listing_Lot_Size'] );
  $template->set ( '@dimensions', $lang['Listing_Dimensions'] );
  $template->set ( '@bathrooms', $lang['Listing_Bathrooms'] );
  $template->set ( '@half_bathrooms', $lang['Listing_Half_Bathrooms'] );
  $template->set ( '@bedrooms', $lang['Listing_Bedrooms'] );
  $template->set ( '@location', $lang['Search_Location'] );
  $template->set ( '@city', $lang['City'] );
  $template->set ( '@address1', $lang['Listing_Address1'] );
  $template->set ( '@address2', $lang['Listing_Address2'] );
  $template->set ( '@zip', $lang['Zip_Code'] );
  $template->set ( '@price', $lang['Listing_Price'] );
  $template->set ( '@directions', $lang['Listing_Directions'] );
  $template->set ( '@year_built', $lang['Listing_Year_Built'] );
  $template->set ( '@buildings', $lang['Listing_Additional_Out_Buildings'] );
  $template->set ( '@appliances', $lang['Listing_Appliances_Included'] );
  $template->set ( '@features', $lang['Listing_Features'] );
  $template->set ( '@garage', $lang['Listing_Garage'] );
  $template->set ( '@garage_cars', $lang['Listing_Garage_Cars'] );
  $template->set ( '@basement', $lang['Listing_Basement'] );
  $template->set ( '@date_added', $lang['Date_Added'] );
  $template->set ( '@date_updated', $lang['Date_Updated'] );
  $template->set ( '@date_upgraded', $lang['Date_Upgraded'] );
  $template->set ( '@hits', $lang['Hits'] );
  $template->set ( '@view_realtor', $lang['View_Realtor'] );
  $template->set ( '@video', $lang['Video_Tour'] );

  $template->set ( '@first_name', $lang['Realtor_First_Name'] );
  $template->set ( '@last_name', $lang['Realtor_Last_Name'] );
  $template->set ( '@company_name', $lang['Realtor_Company_Name'] );
  $template->set ( '@phone', $lang['Realtor_Phone'] );
  $template->set ( '@fax', $lang['Realtor_Fax'] );
  $template->set ( '@mobile', $lang['Realtor_Mobile'] );
  $template->set ( '@email', $lang['Realtor_e_mail'] );
  $template->set ( '@website', $lang['Realtor_Website'] );

  $template->set ( '@slideshow', $lang['Listing_Slideshow'] );
  $template->set ( '@details', $lang['Listing_Details'] );
  $template->set ( '@map', $lang['Listing_Map'] );

	// Custom fields
	$template->set ( '@custom1', show_custom_value ( $db, 'custom1', FIELDS_TABLE ) );
	$template->set ( '@custom2', show_custom_value ( $db, 'custom2', FIELDS_TABLE ) );
	$template->set ( '@custom3', show_custom_value ( $db, 'custom3', FIELDS_TABLE ) );
	$template->set ( '@custom4', show_custom_value ( $db, 'custom4', FIELDS_TABLE ) );
	$template->set ( '@custom5', show_custom_value ( $db, 'custom5', FIELDS_TABLE ) );
	$template->set ( '@custom6', show_custom_value ( $db, 'custom6', FIELDS_TABLE ) );
	$template->set ( '@custom7', show_custom_value ( $db, 'custom7', FIELDS_TABLE ) );
	$template->set ( '@custom8', show_custom_value ( $db, 'custom8', FIELDS_TABLE ) );
	$template->set ( '@custom9', show_custom_value ( $db, 'custom9', FIELDS_TABLE ) );
	$template->set ( '@custom10', show_custom_value ( $db, 'custom10', FIELDS_TABLE ) );

  $template->set ( '@image_url', URL . '/templates/' . $cookie_template . '/images' );

  // Publish template
  $template->publish();

  echo '
   </table>
       ';

	echo table_header ( $lang['View_Map'] );

	echo '<div align="center">';

	//customization options are here
	$map->zoomLevel = $conf['map_zoom'];             //zoom out as far as we can
	$map->setWidth($conf['map_width']);            //pixels
	$map->setHeight($conf['map_height']);           //pixels
	$map->showType = true;         //hide the map | sat | hybrid buttons

	if ($conf['rewrite'] == 'ON')
	$link = URL . '/Listing/' . rewrite(getnamebyid(TYPES_TABLE, $f['type'])) . '/' . $f['id'] . '_' . rewrite($f['title']) . '.html';
	else
	$link = URL . '/viewlisting.php?id=' . $f['id'];

	$link = '<a href="'.$link.'"><strong>' . $f['title'] . '</strong></a> <br />' . $f['address1'] . ' ' . $f['address2'];
	if (strcasecmp($conf['show_postal_code'], 'OFF')) {
	    $link .= '<br />' . $f['zip'];
	}

	if (empty($f['latitude']) || empty($f['longitude'])) {
	   $latlng = $map->addAddress($f['address1'] . ' ' . $f['address2'] . ' ' . $f33['subsubcategory'] . ' ' . $f22['subcategory'] . ' ' . $f11['category'] . ' ' . $f['zip'], $link);
       if ($latlng !== null) {
           list($f['latitude'], $f['longitude']) = explode(',', $latlng);
           $sql = 'UPDATE '.PROPERTIES_TABLE.'
                   SET latitude = "'.floatval($f['latitude']).'",
                       longitude = "'.floatval($f['longitude']).'"
                   WHERE id = '.$f['id'];
           $r_maps = $db->query($sql) or error('Critical Error', mysql_error());
           $db->freeresult($r_maps);
       }
	} else
	$map->addGeoPoint( $f['latitude'], $f['longitude'], $link);

	$map->showMap();

	echo '</div>';

	echo table_footer ();


// Photo Gallery

// Print out all the image gallery items available for this
// listing
$sql = 'SELECT * FROM ' . GALLERY_TABLE . ' WHERE listingid = "' . $f['id'] . '" ORDER BY id';

$r_gallery = $db->query( $sql ) or error ('Critical Error', mysql_error ());

if ($db->numrows($r_gallery) > 0)

{

echo table_header ($lang['Photo_Gallery']);

echo '
<table width="100%" cellpadding="5" cellspacing="0" border="0">
 <tr> ';

$i = 0;

$icount = 0;

$tpl = implode ('', file( PATH . '/templates/' . $cookie_template . '/tpl/gallery.tpl' ));

while ($f_gallery = $db->fetcharray($r_gallery))

{


echo '<td width="33%" align="center" valign="top">';

// Starting a new template
$template = new Template;

// Load image gallery template
$template->load ( $tpl );

// Replace the template variables
$template->set ( 'image', show_gallery_image ('gallery', $f_gallery['id'], $f_gallery['description']) );
$template->set ( 'name', $f_gallery['title'] );
$template->set ( 'description', $f_gallery['description'] );
$template->set ( 'new', newitem ( GALLERY_TABLE, $f_gallery['id'], $conf['new_days']) );
$template->set ( 'updated', updateditem ( GALLERY_TABLE, $f_gallery['id'], $conf['updated_days']) );
$template->set ( 'date_added', printdate($f_gallery['date_added']) );
$template->set ( 'date_updated', printdate($f_gallery['date_updated']) );

// Variable Names

$template->set ( '@name', $lang['Photo_Gallery_Title'] );
$template->set ( '@description', $lang['Photo_Gallery_Description'] );
$template->set ( '@date_added', $lang['Date_Added'] );
$template->set ( '@date_updated', $lang['Date_Updated'] );

// Set background color
$bgcolor = ''; // Background color for all odd listings
$bgcolor2 = $conf['list_background_color_even']; // Background color for all even listings

if ( $i%2 == 0 )
$template->set ( 'bgcolor', $bgcolor );
else
$template->set ( 'bgcolor', $bgcolor2 );

// Publish template
$template->publish();

$i++;

echo '</td>';

$icount++;

if ($icount == 3) { echo '</tr><tr>'; $icount = 0; }

}

echo '
 </tr>
</table>
';

//

echo table_footer ();

}
  }
 else
  echo 'The listing with this ID does not exist.';

 }

else

 echo 'Sorry, ID is not specified';

// Include Recently Visited Listings Box
include ( PATH . '/box-visited-side.php' );

// Template footer
include ( PATH . '/templates/' . $cookie_template . '/footer.php' );

?>